import React, { Component } from "react";
// Redirect组件用于做重定向
import {
  Link,
  Route,
  Switch,
  Redirect,
  useHistory,
  useLocation,
  // useRouteMatch,
  // useParams,
} from "react-router-dom";

class Home extends Component {
  render() {
    return <div>这是首页页面</div>;
  }
}

const About = () => {
  return <div>这是关于页面</div>;
};

const Mine = () => {
  return <div>这是我的页面</div>;
};

const Login = () => {
  // useHistory这个hooks是用来直接获取路由信息下的history对象
  const history = useHistory();
  const location = useLocation();
  // const match = useRouteMatch();
  // const params = useParams();

  const login = () => {
    localStorage.setItem("token", "123");
    // console.log(props);

    // console.log(history);
    // console.log(location);
    // console.log(match);
    // console.log(params);
    history.push(location.state.from);
  };

  return (
    <div>
      这是登录页面 - <button onClick={login}>登录</button>
    </div>
  );
};

// Auth就是用来做路由鉴权
const Auth = (props) => {
  return (
    <Route
      path={props.path}
      render={() => {
        if (localStorage.getItem("token")) {
          return props.children;
        } else {
          // return <Redirect to={`/login?from=${props.path}`}></Redirect>;
          return (
            <Redirect
              to={{
                pathname: "/login",
                state: { from: props.path },
              }}
            ></Redirect>
          );
        }
      }}
    ></Route>
  );
};

class App extends Component {
  render() {
    return (
      <>
        <h2>路由鉴权</h2>
        <ul>
          <li>
            <Link to="/home">首页</Link>
          </li>
          <li>
            <Link to="/about">关于页</Link>
          </li>
          <li>
            <Link to="/mine">我的</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Redirect from="/" to="/home" exact></Redirect>
          <Route path="/home" component={Home}></Route>
          {/* <Route path="/about" component={About}></Route> */}
          <Auth path="/about">
            <About />
          </Auth>
          {/* <Route
            path="/mine"
            render={() => {
              if (localStorage.getItem("token")) {
                return <Mine />;
              } else {
                return <Redirect to="/login"></Redirect>;
              }
            }}
          ></Route> */}
          <Auth path="/mine">
            <Mine />
          </Auth>
          <Route path="/login">
            <Login />
          </Route>
        </Switch>
      </>
    );
  }
}

export default App;
